﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

namespace LG.Common
{
    public partial class StringHelper
    {

        #region 过滤掉 html代码

        /// <summary>
        /// 过滤掉 html代码
        /// </summary>
        /// <param name="html">html源码</param>
        /// <returns></returns>
        public static string RemoveHTML(string html)
        {
            Regex regex = new Regex("<(.[^>]*)>", RegexOptions.IgnoreCase);
            return regex.Replace(html, "");
        }

        /// <summary>
        /// 移除HTML标记
        /// </summary>
        /// <param name="inputString">html源码</param>
        /// <param name="Tag">要设置的标记，如img,h1等</param>
        /// <returns></returns>
        public static string RemoveHtmlTag(string strHtml, string Tag)
        {
            ArrayList TagList = new ArrayList();
            int Top = -1;
            Match m;
            Regex r;
            if (Tag.ToUpper() == "IMG" || Tag.ToUpper() == "BR")
            {
                strHtml = Regex.Replace(strHtml, "\\<" + Tag + @"[\s\S]*?/>", "", RegexOptions.IgnoreCase);
            }
            else
            {
                r = new Regex("\\</?" + Tag, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                for (m = r.Match(strHtml); m.Success; )
                {
                    string TagValue = m.Value;
                    int TagIndex = m.Index;
                    if (TagValue.ToUpper() == @"<" + Tag.ToUpper())
                    {
                        Top = TagList.Add(TagIndex);
                        m = m.NextMatch();
                    }
                    else if (TagValue.ToUpper() == @"</" + Tag.ToUpper())
                    {
                        if (TagList.Count > 0)
                        {
                            int DIndex = (int)TagList[Top];
                            strHtml = strHtml.Remove(DIndex, TagIndex - DIndex + Tag.Length + 3);
                            m = r.Match(strHtml);
                        }
                        else
                        {
                            m = m.NextMatch();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return strHtml;
        }
        #endregion

        public static string ConvertTextToHTML(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                text = text.Replace("<", "&lt;");
                text = text.Replace(">", "&gt;");
                text = text.Replace(" ", "&nbsp;");
                text = text.Replace("\n", "<br/>");
                return text;
            }
            else
            {
                return text;
            }
        }
    }
}
